package com.example.juyixia;

import java.io.BufferedReader;
import java.io.BufferedWriter;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import com.example.adapter.MyAdapterchecked;
import com.example.service.ActiveService;
import com.example.service.MessService;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class NewActiveActivity extends Activity implements OnClickListener{
	private Button mBt_Sure;
	private ImageView mIv_Back;
	private Myinfo myinfo;
	private ListView friends;
	private Map<String, String> ipmap=new HashMap<String, String>();
	static JSONObject actievinfojson;
	List<Map<String, String>> ips=new ArrayList<Map<String, String>>();;
	String rec;
	private int num;//参与人数
	private static List<Map<String, String>> partlist=new ArrayList<Map<String,String>>();
	public static final String bm="utf-8";
	StringBuffer setid;
	private EditText activename;
	StringBuffer allip;
	Map<String, String> activeinfo=new HashMap<String, String>();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);  
        setContentView(R.layout.activity_newactive); 
        friends = (ListView)findViewById(R.id.selectfriend);
        activename=(EditText)findViewById(R.id.activename);
        //给链表添加数据
        List<Map<String, Object>> list=getData();
        //适配器，刚刚重写的！
        MyAdapterchecked myAdapter = new MyAdapterchecked(this, list);
        //设置适配器
        friends.setAdapter(myAdapter);
        initViews();
		
	}
	 public List<Map<String, Object>> getData() {
		    myinfo = (Myinfo)getApplication();
	        List<Myinfo> friendsinfo = myinfo.getUserfriend();
	        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
	        for (Myinfo info : friendsinfo) {
	        	Map<String, Object> map = new HashMap<String, Object>();
	        	map.put("image",  R.drawable.ic_launcher);
	        	map.put("userid", info.getUserid());
	        	map.put("username", info.getUsername());
	        	map.put("userip",info.getUserip());
	        	 list.add(map);
			}
	       
	        return list;
	    }
	 public  boolean isHostConnectable(String host, int port,String currentname) {
			Socket socket = new Socket();
			try {
				socket.connect(new InetSocketAddress(host, port));
				PrintWriter out = new PrintWriter(
						new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), bm)), true);
				out.println(actievinfojson.toString()+"？"+currentname);			
				out.close();
				
				// 关闭Socket
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			} finally {
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return true;
			
		}
	private void initViews() {
		// TODO Auto-generated method stub
		mBt_Sure = (Button) findViewById(R.id.bt_sure);
		mIv_Back = (ImageView) findViewById(R.id.iv_back);
		
		mBt_Sure.setOnClickListener(this);
		mIv_Back.setOnClickListener(this);
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
		switch (v.getId()) {
		case R.id.bt_sure:	
			num=0;
			Toast.makeText(getApplicationContext(),"已发送通知给选中好友，请等待回复！",Toast.LENGTH_SHORT).show();
			activeinfo.clear();
			ips.clear();
			ipmap.clear();
			allip=new StringBuffer("");
			setid=new StringBuffer("");
			//ips=new ArrayList<Map<String, String>>();
			for(int i=0;i<friends.getChildCount();i++){
				//Map<String, String> ipmap=new HashMap<String, String>();
				LinearLayout myitem = (LinearLayout)friends.getChildAt(i);
				CheckBox chkone = (CheckBox) myitem.findViewById(R.id.friendchecked);
				if(chkone.isChecked()){
					num++;				
					TextView friendsname=(TextView) myitem.findViewById(R.id.usersfriendname);
					TextView friendsip=(TextView) myitem.findViewById(R.id.usersfriendip);
					ipmap.put("name", friendsname.getText().toString());
					ipmap.put("ip", friendsip.getText().toString());
					ips.add(ipmap);
					if(i<friends.getChildCount()-1){
					setid.append(friendsname.getText()).append(",");
					allip.append(friendsip.getText()).append(",");
					}else{
						setid.append(friendsname.getText());
						allip.append(friendsip.getText());
					}
				}
				
			}
			activeinfo.put("发起人：",myinfo.getUsername());
			activeinfo.put("发起人ip：", myinfo.getUserip());
			activeinfo.put("活动名：", activename.getText().toString());
			activeinfo.put("参与者：", setid.append(",").append((myinfo.getUsername())).toString());
			activeinfo.put("allip", allip.toString());
			//Toast.makeText(getApplicationContext(),activeinfo.toString(),Toast.LENGTH_SHORT).show();
			 actievinfojson=new JSONObject(activeinfo);
			 Intent intent=new Intent(this,ActiveService.class);
				intent.putExtra("人数", String.valueOf(num));
				intent.putExtra("id",myinfo.getUserid() );
				startService(intent);
			new Thread() {
				public void run() {				
             for (Map<String, String> map : ips) {
            	 if(!isHostConnectable(map.get("ip"), 54321,map.get("name"))){
						continue;
					}
			}
					handler.sendEmptyMessage(0);// 执行完毕后给handler发送一个空消息
				}
				// 定义Handler对象
				private Handler handler = new Handler() {
					@Override
					// 当有消息发送出来的时候就执行Handler的这个方法
					public void handleMessage(Message msg) {
						super.handleMessage(msg);
						// 处理UI
					}
				};
			}.start();

			break;
		case R.id.iv_back:
			finish();

		default:
			break;
		}
		
	
	
	}

}
